package com.jxauaia.contest.controller;

import com.jxauaia.contest.common.response.Result;
import com.jxauaia.contest.model.dto.UserProfileDTO;
import com.jxauaia.contest.model.entity.User;
import com.jxauaia.contest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/users")
@PreAuthorize("hasRole('ADMIN')")
public class AdminUserController {

    private final UserService userService;

    @Autowired
    public AdminUserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 获取所有用户列表
     */
    @GetMapping
    public Result<List<User>> getAllUsers() {
        // 这里需要在UserService中添加findAll方法
        List<User> users = userService.findAll();
        return Result.success(users);
    }

    /**
     * 获取用户详情
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Integer id) {
        User user = userService.findById(id);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        return Result.success(user);
    }

    /**
     * 禁用/启用用户
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasRole('ADMIN') and hasAuthority('PERMISSION_USER_MANAGE')")
    public Result<Boolean> updateUserStatus(@PathVariable Integer id, @RequestParam Integer status) {
        // 这里需要在UserService中添加updateStatus方法
        boolean success = userService.updateStatus(id, status);
        return success ? Result.success("用户状态更新成功", true) : Result.error(400, "用户状态更新失败");
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') and hasAuthority('PERMISSION_USER_MANAGE')")
    public Result<Boolean> deleteUser(@PathVariable Integer id) {
        // 这里需要在UserService中添加deleteUser方法
        boolean success = userService.deleteUser(id);
        return success ? Result.success("用户删除成功", true) : Result.error(400, "用户删除失败");
    }

    /**
     * 更新用户信息（管理员可以更新任何用户的信息）
     */
    @PutMapping("/{id}/profile")
    @PreAuthorize("hasRole('ADMIN') and hasAuthority('PERMISSION_USER_MANAGE')")
    public Result<User> updateUserProfile(@PathVariable Integer id, @RequestBody @Validated UserProfileDTO userProfileDTO) {
        User updatedUser = userService.updateUserProfile(id, userProfileDTO);
        return Result.success("用户信息更新成功", updatedUser);
    }

    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/reset-password")
    @PreAuthorize("hasRole('ADMIN') and hasAuthority('PERMISSION_USER_MANAGE')")
    public Result<Boolean> resetUserPassword(@PathVariable Integer id, @RequestParam String newPassword) {
        // 需要在UserService中添加重置密码的方法
        boolean success = userService.resetPassword(id, newPassword);
        return success ? Result.success("密码重置成功", true) : Result.error(400, "密码重置失败");
    }

    /**
     * 获取系统用户统计信息
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getUserStatistics() {
        List<User> allUsers = userService.findAll();

        // 计算各种统计数据
        long totalUsers = allUsers.size();
        long activeUsers = allUsers.stream().filter(u -> u.getStatus() == 1).count();
        long disabledUsers = allUsers.stream().filter(u -> u.getStatus() == 0).count();
        long adminUsers = allUsers.stream().filter(u -> "admin".equals(u.getUserType())).count();
        long memberUsers = allUsers.stream().filter(u -> "member".equals(u.getUserType())).count();

        // 构建统计结果
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalUsers", totalUsers);
        statistics.put("activeUsers", activeUsers);
        statistics.put("disabledUsers", disabledUsers);
        statistics.put("adminUsers", adminUsers);
        statistics.put("memberUsers", memberUsers);

        return Result.success(statistics);
    }

    /**
     * 批量操作用户状态
     */
    @PutMapping("/batch/status")
    @PreAuthorize("hasRole('ADMIN') and hasAuthority('PERMISSION_USER_MANAGE')")
    public Result<Map<String, Object>> batchUpdateStatus(@RequestBody Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Integer> userIds = (List<Integer>) params.get("userIds");
        Integer status = (Integer) params.get("status");

        if (userIds == null || userIds.isEmpty() || status == null) {
            return Result.error(400, "参数错误");
        }

        int successCount = 0;
        for (Integer userId : userIds) {
            if (userService.updateStatus(userId, status)) {
                successCount++;
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("totalCount", userIds.size());
        result.put("successCount", successCount);
        result.put("failCount", userIds.size() - successCount);

        return Result.success("批量操作完成", result);
    }

    /**
     * 按条件搜索用户
     */
    @GetMapping("/search")
    public Result<List<User>> searchUsers(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String realName,
            @RequestParam(required = false) Integer status) {

        // 需要在UserService中添加搜索用户的方法
        List<User> users = userService.searchUsers(username, email, realName, status);
        return Result.success(users);
    }
}